# 
# 在这个文件中要把所有的从节点的代理关系做好
# 
# 从节点的代理关系包括两种类型：
# 
#  1. 一个是全局代理，也就是相应的软件虽然在从节点上，但在全局是唯一的，例如：部署在某个从节点上的 SSO 
#  2. 另外一种是局部代理，也就是相应的软件在各个从节点或主节点都有一份，例如：部署在每个节点上的 Audit Log, Launch WEB UI
#
for node in current_node.slave_nodes
  server_name = "nginx_of_#{node.name}"
  upstream server_name do
    server node.ip, node.nginx.port
  end
  # TODO Define the location rewrite logic
  location node.name, server_name, :proxy_node => true 
=begin 
  Generated location as:
  
  location /slave/ {
    rewrite ^/slave/(.*)$ $1 break;
    proxy_pass http://slave:80;
  }
=end

  # global, distributed 为Rails容器（Engine）或WebApp容器（Jetty）启动项的属性
  # 所有声明在从节点上，为全局节点的app，需要在主节点暴露出来
  # 默认的app都是global的，非global，也就是会在主节点处冲突的app，如AuditLog, Launch等均要声明自己 :global => false
  #
  #  engine :audit_log, :global => false
  #  engine :launch,    :global => false
  #  jetty  :mo_mgmt,   :global => false
  node.global_apps.each do |app|
    location app.url, server_name
  end
end

# 所有声明需要分布式部署的app
# 分布式部署的申明方式为：
# 在app上声明， :distributed => "global_name"
#   engine :mo_service, :distributed => "global_mo_service"
#

# distributed_apps： app -> node
# such as:
#   app_1#1 => master
#   app_1#2 => slave1
#   app_2#1 => master
#   app_2#2 => slave2
#   app_3#1 => slave1
#   app_3#2 => slave2
# 这些app从 Software::Platform::Engine#engines
#           Software::Environment::Jetty#webapps
# 中得来，都是一些hash而已(indifferent_access)
distributed_apps = all_nodes.inject({}) do |total, node| 
  node.distributed_apps.each{ |app| total[app] = node }
  total
end

#
# grouped_apps: distributed_name => apps
# such as:
#   app_1 => [app_1#1, app_1#2]
#   app_2 => [app_2#1, app_2#2]
#   ...
grouped_apps = distributed_apps.keys.group_by &:distributed

grouped_apps.each do |distributed_name, apps|

  upstream_name = "distributed_upstreams_for_#{distributed_name}"
  upstream upstream_name do 
   # 把这些App所在的节点组成一个upstream集群
    apps.each do |app|
      node = distributed_apps[app]
      server node.ip, node.nginx.port
    end
  end
  location distributed_name, upstream_name 
end